package com.real.fact.web.sale.application;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import com.real.fact.web.application.GeneratePDFReportCommand;

public class GeneratePDFSalesReportCommand extends GeneratePDFReportCommand {

  private Date dateFrom;

  private Date dateEnd;

  private boolean facturaA;

  private boolean facturaB;

  private boolean remito;

  private boolean noFact;

  public GeneratePDFSalesReportCommand(final DataSource dataSource) {
    super(dataSource);
  }

  @Override
  protected String getReportName() {
    return "sales";
  }

  @Override
  protected Map<String, Object> getParameters() {
    Map<String, Object> parameters = new HashMap<String, Object>();
    if (dateFrom != null) {
      parameters.put("DATE_FROM", dateFrom);
    }
    if (dateEnd != null) {
      parameters.put("DATE_END", dateEnd);
    }
    List<String> options = new ArrayList<String>();
    if (facturaA) {
      options.add("A");
    }
    if (facturaB) {
      options.add("B");
    }
    if (remito) {
      options.add("R");
    }
    if (noFact) {
      options.add("NONE");
    }
    parameters.put("TICKET_OPTIONS", options);
    return parameters;
  }

  public void setDateFrom(final Date dateFrom) {
    this.dateFrom = sanitizeFromDate(dateFrom);
  }

  public void setDateEnd(final Date dateEnd) {
    this.dateEnd = sanitizeEndDate(dateEnd);
  }

  private Date sanitizeEndDate(final Date dateEnd) {
    Date retVal = dateEnd;
    if (dateEnd != null) {
      Calendar c = Calendar.getInstance();
      c.setTime(dateEnd);
      c.set(Calendar.HOUR, 0);
      c.set(Calendar.AM_PM, Calendar.AM);
      c.set(Calendar.MINUTE, 0);
      c.set(Calendar.SECOND, 0);
      c.set(Calendar.MILLISECOND, 0);
      c.add(Calendar.DAY_OF_YEAR, 1);
      retVal = c.getTime();
    }
    return retVal;
  }

  private Date sanitizeFromDate(final Date dateFrom) {
    Date retVal = dateFrom;
    if (dateFrom != null) {
      Calendar c = Calendar.getInstance();
      c.setTime(dateFrom);
      c.set(Calendar.HOUR, 0);
      c.set(Calendar.AM_PM, Calendar.AM);
      c.set(Calendar.MINUTE, 0);
      c.set(Calendar.SECOND, 0);
      retVal = c.getTime();
    }
    return retVal;
  }

  public void setFacturaA(boolean facturaA) {
    this.facturaA = facturaA;
  }

  public void setFacturaB(boolean facturaB) {
    this.facturaB = facturaB;
  }

  public void setRemito(boolean remito) {
    this.remito = remito;
  }

  public void setNoFact(boolean noFact) {
    this.noFact = noFact;
  }

  @Override
  public String getFileName() {
    return "ventas_";
  }

}
